package cn.samir.sudoku.image;

import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
import cn.samir.sudoku.R;
import cn.samir.sudoku.db.dao.SavePairDao;
import cn.samir.sudoku.net.HttpManager;
import cn.samir.sudoku.util.ThreadPoolManager;

public class ImageHelper {

	LoadBitmapListener lbl;

	Context context;
	SavePairDao savePairDao;
	ImageView iv;
	
	public ImageHelper(Context context) {
		this.context = context;
		savePairDao = new SavePairDao(context);
	}

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:// 下载完成

				break;
			case 2:// loadbitmap finish
				if (msg.obj == null) {
					if (msg.obj instanceof Bitmap) {
						Bitmap bitmap = (Bitmap) msg.obj;
						iv.setImageBitmap(bitmap);
					}
				}
				break;
			default:
				break;
			}
		};
	};

	public void display(ImageView iv, final String url) {
		this.iv = iv;
		final String path = savePairDao.query(url);
		if (path == null) {
			// 没有，去下载
			ThreadPoolManager.getInstance().addTask(new Runnable() {

				@Override
				public void run() {
					InputStream in = download(url);
					Bitmap bitmap = null;
					if (null != in) {
						bitmap = BitmapFactory.decodeStream(in);
					} else {
						bitmap = BitmapFactory.decodeResource(
								context.getResources(), R.drawable.ic_launcher);
					}

					Message message = Message.obtain();
					message.what = 2;
					message.obj = bitmap;
					handler.sendMessage(message);
				}
			});
		} else {
			ThreadPoolManager.getInstance().addTask(new Runnable() {

				@Override
				public void run() {
					Bitmap bitmap = BitmapFactory.decodeFile(path);
					if (bitmap == null) {
						bitmap = BitmapFactory.decodeResource(
								context.getResources(), R.drawable.ic_launcher);
					}
					Message message = Message.obtain();
					message.what = 1;
					message.obj = bitmap;
					handler.sendMessage(message);

				}
			});
		}
	}

	public InputStream download(String url) {
		HttpGet get = new HttpGet(url);
		try {
			HttpResponse response = HttpManager.execute(get);
			HttpEntity rentity = response.getEntity();
			if (rentity != null) {
				return rentity.getContent();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

}
